package com.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    // 当前跨域请求最大有效时长。这里默认1天
    @Value("${cors.day_num}")
    private long DAY_NUM;
    @Value("${cors.origins}")
    private String ALLOWED_ORIGINS = "*";
    @Value("${cors.methods}")
    private String ALLOWED_METHODS = "GET, POST, PUT, DELETE, OPTIONS";
    @Value("${cors.headers}")
    private String ALLOWED_HEADERS = "*";

    @Bean
    public CorsFilter corsFilter() {
        long MAX_AGE =  DAY_NUM * 60 * 60;
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin(ALLOWED_ORIGINS); // 1 设置访问源地址，或者http://localhost:7060
        corsConfiguration.addAllowedHeader(ALLOWED_HEADERS); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod(ALLOWED_METHODS); // 3 设置访问源请求方法，或设置为"GET", "POST", "DELETE", "PUT"
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
